package com.algorithm.ch1.cjm.tree.model;

import java.util.ArrayList;

/**
 * 树的定义
 */
public class TreeNode {

    public int val;

    public TreeNode left;

    public TreeNode right;

    public TreeNode(int x){
        val = x;
    }

    /**
     * 前序遍历
     * @param root
     * @param res
     */
    public static void preorderTraversal(TreeNode root, ArrayList<Integer> res){

        if(root == null){
            return;
        }

        int rootVal = root.val;
        res.add(rootVal);

        if(root.left != null){
            preorderTraversal(root.left, res);
        }
        if(root.right != null){
            preorderTraversal(root.right, res);
        }
    }

    /**
     * 中序遍历
     * @param root
     * @param res
     */
    public static void inorderTraversal(TreeNode root, ArrayList<Integer> res){

        if(root == null){
            return;
        }

        if(root.left != null){
            inorderTraversal(root.left, res);
        }

        int rootVal = root.val;

        res.add(rootVal);

        if(root.right != null){
            inorderTraversal(root.right, res);
        }

    }

    /**
     * 后序遍历
     * @param root
     * @param res
     */
    public static void postorderTraversal(TreeNode root, ArrayList<Integer> res){

        if(root == null){
            return;
        }

        if(root.left != null){
            postorderTraversal(root.left, res);
        }

        if(root.right != null){
            postorderTraversal(root.right, res);
        }

        int rootVal = root.val;

        res.add(rootVal);
    }

}
